<?php
/**
 * 订单
 * User: yuanxuncheng
 * Date: 2016-12-21
 * Time: 22:39
 */

namespace app\api\model\dao;

use think\Exception;
use think\Log;
use think\Model;
use think\Db;
use app\library\RedisMgr;
use app\library\Flag;

class OrderInfo extends Model
{
    //set talbename
    protected $table = 'order_info';
    //set primary key
    protected $pk = 'order_id';

    /**
     * @desc 增加订单信息
     * @return int
     */
    public function addOrder($param)
    {
        $this->allowField(true)->save($param);
        return $this->data[$this->pk];
    }

    /**
     * @desc 修改订单信息
     * @return int
     */
    public function updateOrder($param)
    {
        $field = array();
        if (isset($param['order_status'])) {
            $field['order_status'] = $param['order_status'];
        }

        $conds = array(
            'order_id' => $param['order_id'],
        );
        return $this->isUpdate(true)->allowField(true)->save($field, $conds);
    }

    /**
     * @param $conds
     * @param $fields
     * @return false|int
     */
    public function updateOrderByConds($conds, $fields)
    {
        return $this->isUpdate(true)->allowField(true)->save($fields, $conds);
    }

    /**
     * @desc 根据条件获取订单
     * @param $conds $fields
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getOrderByCond($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return Db::table($this->table)->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

    public function getCount($conds = [], $field = 'order_id')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';
        return Db::table($this->table)->where($arrCond)->count($field);
    }

    /**
     * @desc 获取订单信息
     * @param $order_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getOrderInfo($order_id)
    {
        $conds = array(
            'order_id' => $order_id,
        );
        $field = '*';
        return Db::table($this->table)->where($conds)->field($field)->find();
    }

    public function getOrderInfoByConds($user_id)
    {
        $conds = [
            'user_id' => ['in', $user_id],
            'order_status' => ['<>', Flag::ORDER_STATUS_DELETE],
            'order_type' => ['=', Flag::ORDER_TYPE_SHANGCHENG],
        ];
        $field = '*';
        return Db::table($this->table)->where($conds)->field($field)->select();
    }

    /**
     * @desc 生成订单ID
     * @return int
     */
    public function generalOrderid()
    {
        $keyPrefix = 'ms:order:';
        $order_id = str_pad(str_replace('.', '', microtime(true)), 14, '0');
        $expireTime = strtotime("+1 day");
        $returnKey = 0;
        $loopIndex = 0;
        while ($returnKey != 1 && $loopIndex++ < 10) { //循环10次获取订单号，保证不重复
            try {
                $order_id = str_pad(str_replace('.', '', microtime(true)), 14, '0');
                $redisKey = $keyPrefix . $order_id;
                $redis = RedisMgr::getInstance([]);
                $returnKey = $redis->inc($redisKey);
                $redis->expireAt($redisKey, $expireTime);
            } catch (Exception $ex) {
                $code = $ex->getCode();
                $msg = $ex->getMessage();
                Log::error(sprintf("CLASS[%s] METHOD[%s] get exception err[%d] msg[%s] file[%s] line[%d] continue re
try",
                    __FILE__, __METHOD__, $code, $msg, $ex->getFile(), $ex->getLine()));
            }
        }
        if ($returnKey == 1) {
            return $order_id;
        } else {
            Log::info('create order_id fail');
            throw new Exception('create order_id fail');
        }
    }

    public function orderListPage()
    {
        $conds = '1=1';
        return $this->where($conds)->order('add_time')->paginate(10);
    }

    public function getOrderStatusAttr($value)
    {
        return Flag::$map_order[$value];
    }

    public function getShippingStatusAttr($value)
    {
        return Flag::$map_shipping[$value];
    }
}
